//****************************************************************
//  pinyinizerOverlay.js
//	Written by: Benny Wong (bdotdub at gmail.com)
//
//  This file will basically grab the selected text, put it in the
//  right click menu, and then open it in a new tab if chosen.
//
//  TODO:
//  - New window depending on setting
//
//***************************************************************

//---
// Variables
//---
var xrequest = new XMLHttpRequest();
// Get the "pinyinizer." branch
var prefs = Components.classes["@mozilla.org/preferences-service;1"].
                    getService(Components.interfaces.nsIPrefService);
prefs = prefs.getBranch("pinyinizer.");


//-------------------
// pinyinizer() - grabs the selected text, and shoots the words into
//	a new tab.
//------------------
function pinyinizer() {
    var focusedWindow = document.commandDispatcher.focusedWindow;
    var text = focusedWindow.getSelection();

    if(text=='') {
    }
    else{
	try {  // get the pref
	    var value = prefs.getCharPref('view');
	    var url = 'http://www.pin1yin1.com/?q=popup&v=1.1&t='+escape(text);
	    if (value == "newtab") {	
        	a=getBrowser().addTab(url);
        	getBrowser().selectedTab = a;
	    }
	    else if (value == "sidebar") {
		toggleSidebar('viewPinyinizer', true);
	    }
	    else alert("Preference error. Sorry!");
	}
	catch(e) {  // if pref doesnt exist, create it
	    if (confirm("First Time Use:\n\n     Press OK to: Open in the sidebar\n     Press Cancel to: Open in a new tab\n\nYou can always change your preference in the options menu."))
		prefs.setCharPref('view', 'sidebar');
	    else
		prefs.setCharPref('view', 'newtab');
	    pinyinizer();
	}
    }
}


// hides the item when appropriate (use same logic as for Back, Stop etc.)
// script written by Stephen Clavering, used in his goHome extension

window.addEventListener("load", countInit, true);
function countInit() {
  document.getElementById("contentAreaContextMenu").addEventListener("popupshowing",countHide,false);
}

function countHide() {
  var cm = gContextMenu;
  var focusedWindow = document.commandDispatcher.focusedWindow;
  var text = focusedWindow.getSelection().toString();
  if (text.length > 15) text = text.substring(0,15) + "..."
  document.getElementById("pinyinizer").hidden = !cm.isTextSelected;
  document.getElementById("pinyinizer").label = "Pinyinize! \"" + text + "\"";
}

//a=window.open('http://www.pin1yin1.com/?q=popup&v=1.1&t='+escape(text),'pinyin','menubar=no,width=500,height=200,status=no,location=no,scrollbars=yes,resizable=yes,dependent=yes,modal=yes,alwaysRaised=yes');
//a.focus();
